package com.shujia;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapTask;
import org.apache.hadoop.mapred.ReduceTask;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;


//class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
//    @Override
//    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
//        //先将Text类型转成java中String类型
//        String line = value.toString();
//        //每一行的数据用空格进行分割
//        String[] strings = line.split(" ");
//        for (String word : strings) {
//            context.write(new Text(word), new LongWritable(1L));
//        }
////        System.out.println("数加：【"+key+"】,value:【"+value+"】");
//
//    }
//}




class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        Long sum = 0L;

        for (LongWritable value : values) {
            long l = value.get();
            sum += l;
        }
        context.write(key, new LongWritable(sum));
//        context.write(new Text("数加："+key.toString()),new LongWritable(0L));
    }
}

/*
        编写mapreduce实现wordcount单词统计
 */
public class WordCountDemo {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //获取hadoop集群的环境配置
        Configuration conf = new Configuration();
        //创建一个任务
        Job job = Job.getInstance(conf);
        //设置reduce的数量
        job.setNumReduceTasks(1);
        //设置任务的名称
        job.setJobName("bigdata17 testMapReduce");
        job.setJarByClass(WordCountDemo.class);

        //设置map类
        job.setMapperClass(MyMapper.class);
        //设置reduce类
        job.setReducerClass(MyReducer.class);

        //设置map任务出来的结果类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce输出结果的key和value的类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //指定数据在HDFS上的路径，这个路径将来需要自己手动传入
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);

//        MapTask
//        ReduceTask


    }
}
